package james.gan.registry.api;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class RegistryCustomCache implements Observer {

	private static final Map<Class<?>, List<SocketAddress>> addressCache = new ConcurrentHashMap<>();

	private final RegistryCenter registryCenter;

	public RegistryCustomCache(RegistryCenter registryCenter) {
		this.registryCenter = registryCenter;
		fetchSocketAddress();
	}

	@Override
	public void update(Observable o, Object arg) {
		fetchSocketAddress();
	}

	/**
	 * 从注册中心获取缓存信息
	 */
	private void fetchSocketAddress() {
		addressCache.clear();
		synchronized (addressCache) {
			Map<Class<?>, List<SocketAddress>> all = registryCenter.findAll();
			addressCache.putAll(all);
		}
	}

	public SocketAddress getLoadBlanceSocketAddress(Class<?> clz) {
		List<SocketAddress> list = null;
		Object obj = addressCache.get(clz);
		if(obj instanceof JSONArray){
			list = ((JSONArray) obj).toJavaList(String.class).stream().map(s->
			{
				System.out.println(s);
				return JSON.parseObject(s, InetSocketAddress.class);
			}).collect(Collectors.toList());
		}
		if (list != null && list.size() > 0) {
			SocketAddress socketAddress = list.get(0);
			return socketAddress;
		}
		throw new IllegalArgumentException("Serivce [" + clz + "] not found");
	}

}
